<template>
  <div class="favorites-container">
    <!-- 左侧导航 -->
    <div class="favorites-sidebar">
      <FavoritesSidebar
        v-model:currentType="currentType"
        v-model:currentFolder="currentFolder"
        :stats="stats"
      />
    </div>

    <!-- 主内容区 -->
    <div class="favorites-main">
      <!-- 顶部工具栏 -->
      <div class="favorites-header">
        <FavoritesToolbar
          v-model:viewMode="viewMode"
          v-model:searchKeyword="searchKeyword"
          :loading="loading"
          @refresh="handleRefresh"
          @create-note="handleCreateNote"
        />
      </div>

      <!-- 内容区域 -->
      <div class="favorites-content">
        <!-- 收藏文件列表 -->
        <FavoriteFileList
          v-if="currentType.startsWith('file')"
          :files="favoriteFiles"
          :loading="loading"
          :view-mode="viewMode"
          :total="total"
          @remove="handleRemoveFavorite"
          @update="handleUpdateFavorite"
          @page-change="handlePageChange"
        />

        <!-- 便签列表 -->
        <NoteList
          v-else-if="currentType.startsWith('note')"
          :notes="notes"
          :loading="loading"
          :view-mode="viewMode"
          :total="total"
          @select="handleNoteSelect"
          @edit="handleEditNote"
          @delete="handleDeleteNote"
          @toggle-favorite="handleToggleNoteFavorite"
          @create="handleCreateNote"
        />

        <!-- 标签管理 -->
        <TagManager 
          v-else-if="currentType === 'tags'"
          :file-tags="fileTags"
          :note-tags="noteTags"
          @create="handleCreateTag"
          @update="handleUpdateTag"
          @delete="handleDeleteTag"
        />
      </div>
    </div>



    <!-- 便签编辑器弹窗 -->
    <NoteEditorDialog
      v-model:visible="showNoteEditor"
      :note="editingNote"
      :folders="noteFolders"
      :note-tags="noteTags"
      @save="handleSaveNote"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

// 组件导入
import FavoritesSidebar from './components/FavoritesSidebar.vue'
import FavoritesToolbar from './components/FavoritesToolbar.vue'
import FavoriteFileList from './components/FavoriteFileList.vue'
import NoteList from './components/NoteList.vue'
import TagManager from './components/TagManager.vue'
import NoteDetail from './components/NoteDetail.vue'
import NoteEditorDialog from './components/NoteEditorDialog.vue'

// API导入
import { favoriteApi } from '@/api/favorite'
import { noteApi, noteFolderApi } from '@/api/note'
import { tagApi } from '@/api/tag'

const { t } = useI18n()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const currentType = ref('file-all') // file-all, file-recent, file-documents, note-all, note-recent, note-favorite, tags
const currentFolder = ref<number | null>(null)
const viewMode = ref<'list' | 'grid'>('list')
const searchKeyword = ref('')

// 分页数据
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 数据状态
const favoriteFiles = ref([])
const notes = ref([])
const fileTags = ref([])
const noteTags = ref([])
const noteFolders = ref([])
const stats = reactive({
  totalFavorites: 0,
  totalNotes: 0,
  favoriteNotes: 0,
  reminderNotes: 0
})

// 选中状态
const selectedNote = ref(null)

// 编辑状态
const showNoteEditor = ref(false)
const editingNote = ref(null)

// 加载初始数据
const loadInitialData = async () => {
  await Promise.all([
    loadStats(),
    loadNoteFolders(),
    loadTags()
  ])
}

// 加载统计数据
const loadStats = async () => {
  try {
    // 只加载总收藏数量
    const response = await favoriteApi.getCategoryStats()
    // {{ AURA-X: Modify - 修复收藏夹统计数据访问路径. Approval: 寸止(ID:fix-stats-access). }}
    const categoryStats = response.data || response

    // 更新总收藏数量
    if (categoryStats && Array.isArray(categoryStats)) {
      stats.totalFavorites = categoryStats.reduce((sum: number, item: any) => sum + (item.count || 0), 0)
    }

    // 加载便签统计数据
    try {
      const response = await noteApi.getNoteStats()
      // {{ AURA-X: Modify - 修复便签统计数据访问路径. Approval: 寸止(ID:fix-stats-access). }}
      const noteStats = response.data || response
      if (noteStats) {
        stats.totalNotes = noteStats.totalNotes || 0
        stats.favoriteNotes = noteStats.favoriteNotes || 0
        stats.reminderNotes = noteStats.reminderNotes || 0
      }
    } catch (error) {
      // console.error('Failed to load note stats:', error)
      // 设置默认值
      stats.totalNotes = 0
      stats.favoriteNotes = 0
      stats.reminderNotes = 0
    }

    // console.log('Stats loaded successfully:', stats)
  } catch (error) {
    // console.error('Failed to load stats:', error)
  }
}

// 加载便签文件夹
const loadNoteFolders = async () => {
  try {
    const response = await noteFolderApi.getFolderTree()
    if (response) {
      noteFolders.value = Array.isArray(response) ? response : []
    }
    // console.log('Note folders loaded successfully')
  } catch (error) {
    // console.error('Failed to load note folders:', error)
    // 设置默认文件夹
    noteFolders.value = [
      { id: 1, name: t('favorites.folders.defaultGroup'), noteCount: 0 },
      { id: 2, name: '工作笔记', noteCount: 0 },
      { id: 3, name: '学习资料', noteCount: 0 }
    ]
  }
}

// 加载标签
const loadTags = async () => {
  try {
    const [fileTagsRes, noteTagsRes] = await Promise.all([
      tagApi.getTags('file'),
      tagApi.getTags('note')
    ])

    if (fileTagsRes) {
      fileTags.value = Array.isArray(fileTagsRes) ? fileTagsRes : []
      // console.log('File tags loaded:', fileTags.value)
    }

    if (noteTagsRes) {
      noteTags.value = Array.isArray(noteTagsRes) ? noteTagsRes : []
      // console.log('Note tags loaded:', noteTags.value)
    }

    // console.log('Tags loaded successfully, fileTags:', fileTags.value.length, 'noteTags:', noteTags.value.length)
  } catch (error) {
    console.error('Failed to load tags:', error)
  }

  // 确保有默认标签数据用于测试
  if (fileTags.value.length === 0) {
    fileTags.value = [
      { id: 1, name: '重要', color: '#F56C6C', type: 'file', usageCount: 5 },
      { id: 2, name: '工作', color: '#409EFF', type: 'file', usageCount: 3 },
      { id: 5, name: '学习', color: '#67C23A', type: 'file', usageCount: 2 }
    ]
  }

  if (noteTags.value.length === 0) {
    noteTags.value = [
      { id: 3, name: '待办', color: '#E6A23C', type: 'note', usageCount: 8 },
      { id: 4, name: '想法', color: '#909399', type: 'note', usageCount: 4 },
      { id: 6, name: '笔记', color: '#4ECDC4', type: 'note', usageCount: 6 }
    ]
  }
}

// 加载主要数据
const loadData = async () => {
  // console.log('🔄 loadData called, currentType:', currentType.value)
  loading.value = true
  try {
    if (currentType.value.startsWith('file')) {
      // console.log('📁 Loading favorite files...')
      await loadFavoriteFiles()
    } else if (currentType.value.startsWith('note')) {
      // console.log('📝 Loading notes...')
      await loadNotes()
    } else if (currentType.value === 'tags') {
      // console.log('🏷️ Loading tags management...')
      // 标签管理不需要加载列表数据，只需要确保标签数据已加载
      // loadTags() 已经在初始化时调用
    } else {
      console.warn('⚠️ Unknown currentType:', currentType.value)
    }
  } catch (error) {
    console.error('❌ Failed to load data:', error)
    ElMessage.error(t('favorites.messages.loadFailed'))
  } finally {
    loading.value = false
  }
}

// 加载收藏文件
const loadFavoriteFiles = async () => {
  try {
    const params: any = {
      page: currentPage.value,
      size: pageSize.value
    }

    // 根据当前类型设置筛选条件
    if (currentType.value === 'file-recent') {
      // 最近收藏
      const response = await favoriteApi.getRecentFavorites(pageSize.value)
      favoriteFiles.value = Array.isArray(response) ? response : []
      total.value = favoriteFiles.value.length
      return
    }

    // 根据分类类型设置筛选条件
    if (currentType.value === 'file-documents') {
      params.category = 'document'
    } else if (currentType.value === 'file-images') {
      params.category = 'image'
    } else if (currentType.value === 'file-videos') {
      params.category = 'video'
    } else if (currentType.value === 'file-others') {
      params.category = 'other'
    }



    // 搜索关键词
    if (searchKeyword.value) {
      params.search = searchKeyword.value
    }

    const response = await favoriteApi.getFavorites(params)
    if (response) {
      // {{ AURA-X: Modify - 修复数据访问路径，从response.records改为response.data.records. Approval: 寸止(ID:fix-data-access). }}
      if (response.data && response.data.records && Array.isArray(response.data.records)) {
        // 分页数据
        favoriteFiles.value = response.data.records
        total.value = response.data.total || 0
      } else if (Array.isArray(response)) {
        // 非分页数据（兼容旧格式）
        favoriteFiles.value = response
        total.value = response.length
      } else {
        // 数据格式不正确，设置为空数组
        console.warn('Invalid response format:', response)
        favoriteFiles.value = []
        total.value = 0
      }
    } else {
      favoriteFiles.value = []
      total.value = 0
    }

    // console.log('Favorite files loaded successfully:', favoriteFiles.value.length)
  } catch (error) {
    // console.error('Failed to load favorite files:', error)
    ElMessage.error(t('favorites.messages.loadFilesFailed'))
    favoriteFiles.value = []
    total.value = 0
  }
}

// 加载便签
const loadNotes = async () => {
  try {
    const params: any = {
      page: currentPage.value,
      size: pageSize.value
    }

    // 根据当前类型设置筛选条件
    if (currentType.value === 'note-recent') {
      const response = await noteApi.getRecentNotes(pageSize.value)
      notes.value = Array.isArray(response) ? response : []
      total.value = notes.value.length
      return
    }

    if (currentType.value === 'note-favorite') {
      const response = await noteApi.getFavoriteNotes(pageSize.value)
      notes.value = Array.isArray(response) ? response : []
      total.value = notes.value.length
      return
    }

    // 根据便签类型设置筛选参数
    if (currentType.value === 'note-all') {
      // 全部便签，不设置特殊筛选条件
    } else if (currentType.value === 'note-reminder') {
      // 待办事项筛选：只显示有提醒时间的便签
      params.hasReminder = true
    }

    if (currentFolder.value) {
      params.folderId = currentFolder.value
    }

    if (searchKeyword.value) {
      params.search = searchKeyword.value
    }

    // console.log('Loading notes with params:', params)
    const response = await noteApi.getNotes(params)
    // console.log('Notes API response:', response)

    if (response) {
      // {{ AURA-X: Modify - 修复便签数据访问路径，从response.records改为response.data.records. Approval: 寸止(ID:fix-data-access). }}
      if (response.data && response.data.records && Array.isArray(response.data.records)) {
        // 分页数据
        notes.value = response.data.records
        total.value = response.data.total || 0
        // console.log('📝 分页数据 - notes:', notes.value.length, 'total:', total.value)
      } else if (Array.isArray(response)) {
        // 非分页数据（兼容旧格式）
        notes.value = response
        total.value = response.length
        // console.log('📝 非分页数据 - notes:', notes.value.length, 'total:', total.value)
      } else {
        console.warn('Invalid notes response format:', response)
        notes.value = []
        total.value = 0
      }
    } else {
      notes.value = []
      total.value = 0
    }

    // console.log('Notes loaded successfully:', notes.value.length)
  } catch (error) {
    console.error('Failed to load notes:', error)
    ElMessage.error(t('favorites.messages.loadNotesFailed') + ': ' + (error.message || t('favorites.messages.operationFailed')))
    notes.value = []
    total.value = 0
  }
}

// 页面标题
document.title = `收藏夹 - RickPan`

// 监听类型变化
watch([currentType, currentFolder, searchKeyword], () => {
  loadData()
}, { immediate: true })

// 生命周期
onMounted(() => {
  loadInitialData()
})

// 事件处理
const handleRefresh = () => {
  loadData()
}

const handleCreateNote = () => {
  editingNote.value = null
  showNoteEditor.value = true
}



const handleNoteSelect = (note: any) => {
  selectedNote.value = note
}

const handleCloseDetail = () => {
  selectedNote.value = null
}

const handleRemoveFavorite = async (file: any) => {
  try {
    await favoriteApi.removeFavorite(file.fileId)
    ElMessage.success(t('favorites.messages.removeSuccess'))
    loadData()
    loadStats() // 刷新统计数据
  } catch (error) {
    console.error('Failed to remove favorite:', error)
    ElMessage.error(t('favorites.messages.removeFailed'))
  }
}

const handleUpdateFavorite = async (file: any, data: any) => {
  try {
    // 使用收藏记录的ID而不是文件ID
    const favoriteId = file.favoriteId || file.id
    await favoriteApi.updateFavorite(favoriteId, data)
    ElMessage.success(t('favorites.messages.updateSuccess'))
    loadData()
    loadStats() // 刷新统计数据
  } catch (error) {
    console.error('Failed to update favorite:', error)
    ElMessage.error(t('favorites.messages.updateFailed') + ': ' + (error.message || t('favorites.messages.operationFailed')))
  }
}

const handleEditNote = (note: any) => {
  editingNote.value = note
  showNoteEditor.value = true
}

const handleDeleteNote = async (note: any) => {
  try {
    await noteApi.deleteNote(note.id)
    ElMessage.success(t('favorites.messages.deleteSuccess'))
    loadData()
    loadStats() // 刷新统计数据
    // 如果当前选中的是被删除的便签，清空选中状态
    if (selectedNote.value?.id === note.id) {
      selectedNote.value = null
    }
  } catch (error) {
    console.error('Failed to delete note:', error)
    ElMessage.error(t('favorites.messages.deleteFailed'))
  }
}

const handleToggleNoteFavorite = async (note: any) => {
  try {
    await noteApi.toggleFavorite(note.id)
    ElMessage.success(t('favorites.messages.operationSuccess'))
    loadData()
    loadStats() // 刷新统计数据
  } catch (error) {
    console.error('Failed to toggle note favorite:', error)
    ElMessage.error(t('favorites.messages.operationFailed'))
  }
}

const handleSaveNote = async (noteData: any) => {
  try {
    if (editingNote.value) {
      // 更新便签
      await noteApi.updateNote(editingNote.value.id, noteData)
      ElMessage.success(t('favorites.messages.updateSuccess'))
    } else {
      // 创建便签
      await noteApi.createNote(noteData)
      ElMessage.success(t('favorites.messages.createSuccess'))
    }

    showNoteEditor.value = false
    editingNote.value = null
    loadData()
    loadStats() // 刷新统计数据
  } catch (error) {
    console.error('Failed to save note:', error)
    ElMessage.error(t('favorites.messages.saveFailed'))
  }
}

const handleUpdateNote = async (note: any, data: any) => {
  try {
    await noteApi.updateNote(note.id, data)
    ElMessage.success(t('favorites.messages.updateSuccess'))
    loadData()
    loadStats() // 刷新统计数据
  } catch (error) {
    console.error('Failed to update note:', error)
    ElMessage.error(t('favorites.messages.updateFailed'))
  }
}

const handleCreateTag = async (tagData: any) => {
  try {
    await tagApi.createTag(tagData)
    ElMessage.success(t('favorites.messages.createSuccess'))
    loadTags()
  } catch (error) {
    console.error('Failed to create tag:', error)
    ElMessage.error(t('favorites.messages.createFailed'))
  }
}

const handleUpdateTag = async (tag: any, data: any) => {
  try {
    await tagApi.updateTag(tag.id, data)
    ElMessage.success(t('favorites.messages.updateSuccess'))
    loadTags()
  } catch (error) {
    console.error('Failed to update tag:', error)
    ElMessage.error(t('favorites.messages.updateFailed'))
  }
}

const handleDeleteTag = async (tag: any) => {
  try {
    await tagApi.deleteTag(tag.id)
    ElMessage.success(t('favorites.messages.deleteSuccess'))
    loadTags()
  } catch (error) {
    console.error('Failed to delete tag:', error)
    ElMessage.error(t('favorites.messages.deleteFailed'))
  }
}

// 分页事件处理
const handlePageChange = (page: number, size: number) => {
  currentPage.value = page
  pageSize.value = size
  loadData()
}
</script>

<style scoped>
.favorites-container {
  display: flex;
  height: calc(100vh - 60px); /* 减去顶部导航栏高度 */
  background: var(--el-bg-color);
}

.favorites-sidebar {
  width: 240px;
  border-right: 1px solid var(--el-border-color);
  background: var(--el-bg-color-page);
  overflow-y: auto;
}

.favorites-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-width: 0; /* 防止flex子项溢出 */
}

.favorites-header {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color);
  background: var(--el-bg-color);
  flex-shrink: 0; /* 防止头部被压缩 */
}

.favorites-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  min-height: 0; /* 确保可以滚动 */
}


</style>
